package com.hyq.hm.hyperlandmark.view;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.hyq.hm.hyperlandmark.activity.MainActivity;
import com.hyq.hm.hyperlandmark.app.AppConstance;
import com.hyq.hm.hyperlandmark.tools.CameraOverlap;
import com.hyq.hm.hyperlandmark.tools.EGLUtils;
import com.hyq.hm.hyperlandmark.tools.ScrenUtils;
import com.hyq.hm.hyperlandmark.tools.ThreadPoolManager;

import java.util.concurrent.ThreadPoolExecutor;

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {

    private Paint p = new Paint();
    private float scaleX = 1, scaleY = 1;
    private int barHeight;
    private Path topPath = new Path();
    private Path bottomPath = new Path();

    public MySurfaceView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MySurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MySurfaceView(Context context) {
        super(context);
        init();
    }

    private void init() {
        Log.d("TAG", "init");

        SurfaceHolder holder = getHolder();
        holder.addCallback(this);
        setZOrderOnTop(true);
        getHolder().setFormat(PixelFormat.TRANSLUCENT);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Log.d("TAG", "onSizeChanged");
        super.onSizeChanged(w, h, oldw, oldh);

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d("TAG", "surfaceCreated");
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        Log.d("TAG", "surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d("TAG", "surfaceDestroyed");
    }

    public void dodraw(final Point[] topPoints, final Point[] bottomPoints, int viewWidth, final int viewHeight, final int index, final int dy) {
        synchronized (MySurfaceView.class) {
            ThreadPoolManager.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    Log.d("TAG", "DrawThread run");
                    Canvas canvas = null;
                    synchronized (getHolder()) {
                        try {
                            canvas = getHolder().lockCanvas();
                            if (canvas == null) {
                                return;
                            }
                            Log.d("TAG", "Drawing-------------");

                            topPath.reset();
                            bottomPath.reset();
                            /**
                             * T-show 坐标
                             */
                            if (barHeight == 0) {
                                barHeight = ScrenUtils.getStatusBarHeight(getContext()) * 2;
                            }
                            if (scaleX == 1 || scaleY == 1) {
                                scaleX = MainActivity.screenW * 1.0f / (viewHeight - barHeight);
                                scaleY = viewHeight * 1.0f / CameraOverlap.PREVIEW_HEIGHT;
                            }
                            function_Catmull_Rom(topPoints, 300, topPath, scaleX, scaleY, dy);
                            function_Catmull_Rom(bottomPoints, 300, bottomPath, scaleX, scaleY, dy);

                            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                            canvas.drawColor(Color.TRANSPARENT);


                            p.setColor(AppConstance.colors[index]);
                            p.setAntiAlias(true); //抗锯齿
                            p.setStyle(Paint.Style.FILL);
                            p.setAlpha(AppConstance.ALPA);
                            p.setMaskFilter(new BlurMaskFilter(5, BlurMaskFilter.Blur.SOLID));
                            canvas.drawPath(topPath, p);
                            canvas.drawPath(bottomPath, p);

                        } catch (Exception e) {
                            Log.d("TAG", "throw Exception in run");
                            e.printStackTrace();

                        } finally {
                            // 解锁Canvas，并渲染当前图像  
                            if (canvas != null) {
                                getHolder().unlockCanvasAndPost(canvas);
                            }
                        }
                    }
                }
            });
        }

    }

    public void clearCanvas() {
        Canvas canvas = null;
        synchronized (getHolder()) {
            try {
                canvas = getHolder().lockCanvas();
                if (canvas == null) {
                    return;
                }
                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                canvas.drawColor(Color.TRANSPARENT);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 解锁Canvas，并渲染当前图像  
                if (canvas != null) {
                    getHolder().unlockCanvasAndPost(canvas);
                }
            }
        }
    }

    public void function_Catmull_Rom(Point[] point, int cha, Path path, float scaleX,
                                     float scaleY, int dy) {
        if (point.length < 4 || point[0] == null) {
            return;
        }
        path.moveTo(point[0].x * scaleX + dy, point[0].y * scaleY);
        for (int index = 1; index < point.length - 2; index++) {
            if (point[index].x == 0 || point[index].y == 0 || index == 6) {
                continue;
            }
            Point p0 = point[index - 1];
            Point p1 = point[index];
            Point p2 = point[index + 1];
            Point p3 = point[index + 2];
            for (int i = 1; i <= cha; i++) {
                float t = i * (1.0f / cha);
                float tt = t * t;
                float ttt = tt * t;

                Point pi = new Point(); // intermediate point
                pi.x = (int) (0.5 * (2 * p1.x + (p2.x - p0.x) * t + (2 * p0.x - 5 * p1.x + 4 * p2.x - p3.x) * tt + (3 * p1.x - p0.x - 3 * p2.x + p3.x)
                        * ttt));
                pi.y = (int) (0.5 * (2 * p1.y + (p2.y - p0.y) * t + (2 * p0.y - 5 * p1.y + 4 * p2.y - p3.y) * tt + (3 * p1.y - p0.y - 3 * p2.y + p3.y)
                        * ttt));
                if (pi.x != 0 && pi.y != 0) {
                    path.lineTo(pi.x * scaleX + dy, pi.y * scaleY);
                }
            }
        }
        path.lineTo(point[point.length - 1].x * scaleX + dy, point[point.length - 1].y * scaleY);
    }

    /**
     * 暖意特效
     *
     * @param bmp     原图片
     * @param centerX 光源横坐标
     * @param centerY 光源纵坐标
     * @return 暖意特效图片
     */
    public static Bitmap warmthFilter(Bitmap bmp, int centerX, int centerY) {
        final int width = bmp.getWidth();
        final int height = bmp.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

        int pixR = 0;
        int pixG = 0;
        int pixB = 0;

        int pixColor = 0;

        int newR = 0;
        int newG = 0;
        int newB = 0;
        int radius = Math.min(centerX, centerY);

        final float strength = 150F; // 光照强度 100~150
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        int pos = 0;
        for (int i = 1, length = height - 1; i < length; i++) {
            for (int k = 1, len = width - 1; k < len; k++) {
                pos = i * width + k;
                pixColor = pixels[pos];

                pixR = Color.red(pixColor);
                pixG = Color.green(pixColor);
                pixB = Color.blue(pixColor);

                newR = pixR;
                newG = pixG;
                newB = pixB;

                // 计算当前点到光照中心的距离，平面座标系中求两点之间的距离
                int distance = (int) (Math.pow((centerY - i), 2) + Math.pow(centerX - k, 2));
                if (distance < radius * radius) {
                    // 按照距离大小计算增加的光照值
                    int result = (int) (strength * (1.0 - Math.sqrt(distance) / radius));
                    newR = pixR + result;
                    newG = pixG + result;
                    newB = pixB + result;
                }

                newR = Math.min(255, Math.max(0, newR));
                newG = Math.min(255, Math.max(0, newG));
                newB = Math.min(255, Math.max(0, newB));

                pixels[pos] = Color.argb(255, newR, newG, newB);
            }
        }

        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
}